import re
from django.contrib.auth.backends import ModelBackend
from .models import User

# 重写登录
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try :
            if re.match('^1[3-9]\d{9}',username):
                user = User.objects.get(mobile=username)

            else:
                user = User.objects.get(username = username)

        except:
            return None

        # 校验密码
        if user.check_password(password):
            return user
        else:
            return None

# 重新定义token返回值
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token':token,
        'id':user.id,
        'mobile':user.mobile,
        'avatar':user.avatar,
        'username':user.username
    }